package org.dfl.plugin.views.actions;

import org.dfl.plugin.DflPlugin;
import org.dfl.plugin.views.ViewsManager;
import org.dfl.plugin.views.debug.model.HistoryColTreeElem;
import org.dfl.plugin.views.debug.model.HistoryTreeElem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * action that provide adding a subhistory (unnesting information in a history unnesting list).
 * It's used in a HistoriesTreeView (see mapping in plugin.xml file)
 * @author Piotr Wlodarczyk
 *
 */
public class AddSubhistoryAction extends ActionDelegate implements IObjectActionDelegate{
	
	private IStructuredSelection selection = StructuredSelection.EMPTY;

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection sel) {
		if(sel instanceof IStructuredSelection)
			selection = (IStructuredSelection) sel;
		else 
			selection = StructuredSelection.EMPTY;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		if (selection.isEmpty())
			return;
		Object parent = selection.getFirstElement();
		if (parent instanceof HistoryTreeElem) {
			HistoryTreeElem parentElem = (HistoryTreeElem) parent;
			synchronized (DflPlugin.class) {
				parentElem.addNewFirstChild();
			}
			ViewsManager.refreshViews(parentElem);
		} else if (parent instanceof HistoryColTreeElem) {
			HistoryColTreeElem parentElem = (HistoryColTreeElem) parent;
			synchronized (DflPlugin.class) {
				((HistoryTreeElem) parentElem.getParent()).addNewChildAfter(parentElem);
			}
			ViewsManager.refreshViews(parentElem.getParent());
		}
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}
}
